<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="queryParams.name" clearable placeholder="请输入内容" class="search-main" @clear="getCompanyList" />
      <el-button type="primary" @click="getCompanyList">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/addCompany')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="handleExpandChange">
        <!-- 表格展开项 -->
        <el-table-column type="expand">
          <template #default>
            <el-table empty-text :data="rentInfoList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="{row}">
                  <span>{{ formartStatus(row.status) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="{row}">
                  <el-button
                    :disabled="row.status === 3"
                    size="mini"
                    type="text"
                    @click="outRent(row.id)"
                  >退租</el-button>
                  <el-button size="mini" type="text" :disabled="row.status !== 3">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button size="mini" type="text" @click="addContractBtn(row.id)">添加合同</el-button>
            <el-button size="mini" type="text" @click="$router.push(`/companyDetail/${row.id}`)">查看</el-button>
            <el-button size="mini" type="text" @click="$router.push(`/addCompany/${row.id}`)">编辑</el-button>
            <el-popconfirm title="是否确定删除当前企业吗？" @confirm="delBtn(row.id)">
              <el-button slot="reference" size="mini" type="text" style="margin-left: 10px;">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next, sizes"
        :page-size.sync="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        background
        :current-page.sync="queryParams.page"
        @current-change="getCompanyList"
        @size-change="handleSizeChange"
      />
    </div>
    <!-- 合同弹层 -->
    <el-dialog title="添加合同" :visible="rentDialogVisible" width="580px" @close="closeDialog">
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option v-for="item in rentBuildingList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload ref="upload" action="#" :http-request="uploadContactFile" :before-upload="beforeUpload">
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmBtn">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getRentBuildingListAPI } from '@/api/build'
import { addContractAPI, delCompanyAPI, getCompanyListAPI, getContractListAPI, outRentAPI, uploadFileAPI } from '@/api/park'

export default {
  data() {
    return {
      list: [],
      queryParams: {
        name: '',
        page: 1,
        pageSize: 10
      },
      total: 0,
      rentDialogVisible: false,
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件', trigger: 'blur' }
        ]
      },
      rentBuildingList: [],
      rentInfoList: []
    }
  },
  created() {
    this.getCompanyList()
  },
  methods: {
    // 获取企业列表
    async getCompanyList() {
      const res = await getCompanyListAPI(this.queryParams)
      console.log('获取企业列表', res)
      this.list = res.data.rows
      this.total = res.data.total
    },
    // 列表展示条目发生变化
    handleSizeChange() {
      this.queryParams.page = 1
      this.getCompanyList()
    },
    // 删除企业
    async delBtn(id) {
      // 1. 发送请求
      await delCompanyAPI(id)
      // 2. 提示用户
      this.$message.success('删除成功')
      // 3. 边界处理
      if (this.list.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      // 4. 重新获取数据 -- 更新视图
      this.getCompanyList()
    },
    // 添加合同
    addContractBtn(id) {
      // 1. 显示弹层
      this.rentDialogVisible = true
      // 2. 获取企业id
      this.rentForm.enterpriseId = id
      // 3. 获取可租赁楼宇列表
      this.getRentBuildingList()
    },
    // 关闭弹层
    closeDialog() {
      this.$refs.addForm.resetFields()
      this.rentForm.rentTime = []
      this.$refs.upload.clearFiles()
      this.rentDialogVisible = false
    },
    // 获取可租赁楼宇列表
    async getRentBuildingList() {
      const res = await getRentBuildingListAPI()
      this.rentBuildingList = res.data
    },
    // 文件校验
    beforeUpload(file) {
      console.log(file)

      const allowImgType = [
        'application/msword', // .doc
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
        'application/pdf' // .pdf
      ].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!allowImgType) {
        this.$message.error('上传合同文件只能是 doc/docx/pdf 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传合同文件大小不能超过 5MB!')
      }
      return allowImgType && isLt5M
    },
    // 上传合同文件
    async uploadContactFile(fileData) {
      console.log(fileData)
      // 1. 处理FormData
      const { file } = fileData
      const fd = new FormData()
      fd.append('file', file)
      fd.append('type', 'contract')
      // 2. 上传并赋值 ---------------Todo 这个接口有问题？
      const res = await uploadFileAPI(fd)
      console.log('上传成功了', res)
      const { id, url } = res.data
      this.rentForm.contractId = id
      this.rentForm.contractUrl = url
      // 单独校验表单
      this.$refs.addForm.validate('contractId')
    },
    // 添加合同
    async confirmBtn() {
      // 1. 校验表单
      await this.$refs.addForm.validate()
      console.log('校验ton过')
      const { buildingId, contractUrl, contractId, type, enterpriseId, rentTime } = this.rentForm
      // 2. 发送请求
      await addContractAPI({
        buildingId,
        contractUrl,
        contractId,
        type,
        enterpriseId,
        startTime: rentTime[0],
        endTime: rentTime[1]
      })
      // 3. 提示用户
      this.$message.success('添加合同成功')
      // 4. 重置表单 + 管理弹层
      this.closeDialog()
      // 5. 获取企业列表
      this.getCompanyList()
    },
    // 展开行处理
    async handleExpandChange(row, expandedRows) {
      // console.log('展开行被展开了', row, expandedRows)
      // 只有在行被展开的时候发送请求
      const isExpend = expandedRows.some(item => item.id === row.id)
      if (isExpend) {
        const res = await getContractListAPI(row.id)
        console.log('展开行被展开了', res)
        this.rentInfoList = res.data
      }
    },
    // 退租
    async outRent(id) {
      await this.$confirm('确定要退租吗？', '提示', {
        type: 'warning'
      })
      await outRentAPI(id)
      this.$message.success('退租成功')
      this.getCompanyList()
    },
    // 格式化合同状态
    formartStatus(status) {
      if (status === 0) {
        return '待生效'
      }
      if (status === 1) {
        return '生效中'
      }
      if (status === 2) {
        return '已到期'
      }
      if (status === 3) {
        return '已退租'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
